//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package fs_api_serv

import (
	"context"

	"gitcode.com/eteam/api-server/dao/board_dao"
	"gitcode.com/eteam/api-server/dao/fs_dao"
	"gitcode.com/eteam/proto-gen-go.git/fs_api"
)

type _FsPermCheck struct{}

func (fpc *_FsPermCheck) CheckAllowRead(ctx context.Context, userId string, fsItem *fs_dao.FsInfoDbItem, fileItem *fs_dao.FileInfoDbItem) (bool, error) {
	if fpc == nil || fsItem == nil || fileItem == nil {
		return false, nil
	}
	if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER {
		//用户头像始终可读
		if fileItem.OwnerType == fs_api.FILE_OWNER_TYPE_FILE_OWNER_TYPE_USER_PHOTO {
			return true, nil
		}
		return userId == fsItem.OwnerId, nil
	} else if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_BOARD {
		return board_dao.MemberInfoDao.Exist(ctx, fsItem.OwnerId, userId)
	}
	return false, nil
}

func (fpc *_FsPermCheck) CheckAllowWrite(ctx context.Context, userId string, fsItem *fs_dao.FsInfoDbItem, reqFsId string) (bool, error) {
	if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER {
		return userId == fsItem.OwnerId, nil
	} else if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_BOARD {
		return board_dao.MemberInfoDao.Exist(ctx, fsItem.OwnerId, userId)
	}
	return false, nil
}

func (fpc *_FsPermCheck) CheckAllowSetOwner(ctx context.Context, userId string, fsItem *fs_dao.FsInfoDbItem,
	fileItem *fs_dao.FileInfoDbItem, ownerType fs_api.FILE_OWNER_TYPE, ownerId string) (bool, error) {
	if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER {
		if fileItem.OwnerType != fs_api.FILE_OWNER_TYPE_FILE_OWNER_TYPE_NONE {
			return false, nil
		}
		if ownerType == fs_api.FILE_OWNER_TYPE_FILE_OWNER_TYPE_USER_PHOTO {
			return userId == ownerId, nil
		}
	} else if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_BOARD {
		if fileItem.OwnerType != fs_api.FILE_OWNER_TYPE_FILE_OWNER_TYPE_NONE {
			return false, nil
		}
		return board_dao.MemberInfoDao.Exist(ctx, fsItem.OwnerId, userId)
	}
	return false, nil
}

func (fpc *_FsPermCheck) CheckAllowStatFs(ctx context.Context, userId string, fsItem *fs_dao.FsInfoDbItem) (bool, error) {
	if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_USER {
		return userId == fsItem.OwnerId, nil
	} else if fsItem.OwnerType == fs_api.FS_OWNER_TYPE_FS_OWNER_TYPE_BOARD {
		return board_dao.MemberInfoDao.Exist(ctx, fsItem.OwnerId, userId)
	}
	return false, nil
}
